package org.mymail.mail;

import java.io.BufferedReader;

import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;



// Referenced classes of package org.mymail.mail:
//            PopMailSession, MailFwdType, UpdateSubscribers

public class ReadMail
{

	public static void main(String args[])
    {
      readMail();
    }

	public static void readMail()
	{
		//PropertyConfigurator.configure("config/log4j.properties");
	    Session session = (new PopMailSession()).createSession();
	    try
	    {
	        Store store = session.getStore("pop3");
	        store.connect("pop.gmail.com", "sharath.ravindran2@gmail.com", "uvce2005.2005");
	        Folder folder = store.getFolder("INBOX");
	        folder.open(Folder.READ_ONLY);
	        Message m[] = folder.getMessages();
	        Date yesterdaysDate = ReadMail.getYesterDaysDate();
	        for(int i = 0 ; i < m.length; i++)
	        {
	            String subject = m[i].getSubject();
	            System.err.println("Subject of m["+i+"] - "+subject);
	            javax.mail.Address a2[] = m[i].getFrom();
	            InternetAddress ia = (InternetAddress)a2[0];
	            String from  = ia.getAddress();
	            System.err.println("Message Number : "+m[i].getMessageNumber());
	            if (m[i].getSentDate().after(yesterdaysDate)
						&& subject.contains("Unsubscribe Me - ")) {
					String service = subject.substring(
							subject.indexOf("-") + 2, subject.length());
					int mailFwdType = MailFwdType.getIntFromString(service);
					UpdateSubscribers.removeSubscriber(a2[0], mailFwdType);
				} else if (subject.contains("Subscribe-Friends")) {
					m[i].writeTo(System.out);
					BufferedReader in = new BufferedReader(new InputStreamReader(m[i].getInputStream()));
					UpdateSubscribers.addSubscribers(in, from);
				}
	        }
	        
	        folder.close(true);
	        store.close();
	        session = null;
	    }
	    catch(Throwable e)
	    {
	    	//readMail();
	    }
	}
	
	
    static Date getYesterDaysDate()
    {
        Calendar cal = new GregorianCalendar();
        cal.add(5, -1);
        Date date = cal.getTime();
        return date;
    }
}